package com.peng.leetcode.tree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * IsCousinscByBfs
 *
 * 993. 二叉树的堂兄弟节点
 *
 *@author lupeng
 *Created on 2021-05-19
 */
public class IsCousinscByBfs {

    public static void main(String[] args) {
        TreeNode root = TreeMain.array2tree(new Integer[]{1, 2, 3, null, 4, null, 5});
        System.out.println(new IsCousinscByBfs().isCousins(root, 5, 4));
    }

    private int x;
    private TreeNode xParent;
    private int xDepth;
    private boolean xFound = false;

    private int y;
    private TreeNode yParent;
    private int yDepth;
    private boolean yFound = false;

    public boolean isCousins(TreeNode root, int x, int y) {
        this.x = x;
        this.y = y;
        Queue<TreeNode> nodeQueue = new LinkedList<>();
        Queue<Integer> depthQueue = new LinkedList<>();
        nodeQueue.offer(root);
        depthQueue.offer(0);
        update(root, 0, null);


        while (!nodeQueue.isEmpty()) {
            TreeNode node = nodeQueue.poll();
            Integer depth = depthQueue.poll();

            if (node.left != null) {
                nodeQueue.offer(node.left);
                depthQueue.offer(depth + 1);
                update(node.left, depth + 1, node);
            }
            if (node.right != null) {
                nodeQueue.offer(node.right);
                depthQueue.offer(depth + 1);
                update(node.right, depth + 1, node);
            }
            if (xFound && yFound) {
                break;
            }
        }
        return xDepth == yDepth && xParent != yParent;
    }

    private void update(TreeNode node, int depth, TreeNode parent) {
        if (node.val == x) {
            this.xParent = parent;
            this.xDepth = depth;
            this.xFound = true;
        }
        if (node.val == y) {
            this.yParent = parent;
            this.yDepth = depth;
            this.yFound = true;
        }
    }

}
